articles

Home / DeveloperSection / Articles / Error Handling in JavaScript

Error Handling in JavaScript

Error Handling in JavaScript

Ashutosh Kumar Verma 197 25-Jun-2024

JavaScript Error Handling

Error handling in JavaScript is an important part of writing robust and reliable code. It’s about handling errors nicely so that your application can handle unexpected situations without crashing or being unwanted. Here is a detailed overview of error handling in JavaScript,

Types of Errors

Syntax errors- These are errors in code syntax, which make it impossible to parse and execute scripts.

if (true {
   console.log("This is a syntax error");
}

Runtime Errors- These occur during execution of a script, such as trying to call a method on an undefined variable.

let obj;
obj.method();  // Runtime error: Cannot read property 'method' of undefined

Logical errors- These are errors in the logic of the code that produce incorrect results but do not stop its execution.

let total = 10 + "5";  // Logical error: total will be '105' instead of 15

 

Error Handling Mechanisms

Here are several types of handling errors in JavaScript as follows,

try...catch...finally- This is the basic way to handle exceptions in JavaScript. Code is executed in the try block, and if an error occurs, control is transferred to the catch block. The finally block is executed regardless of whether an error occurred or not.

Syntax-

try {
   // Code that may throw an error
} catch (error) {
   // Code to handle the error
} finally {
   // Code to run regardless of an error
}

Example-

try {
   let result = riskyOperation();
} catch (error) {
   console.error("An error occurred: ", error.message);
} finally {
   console.log("This will run regardless of an error.");
}

throw Statement- You can use a throw statement to create your own error.

Syntax-

throw new Error("Something went wrong!");

Example-

function checkAge(age) {
   if (age < 18) {
       throw new Error("Age must be at least 18");
   }
}
try {
   checkAge(15);
} catch (error) {
   console.error(error.message);
}

 

Custom Error Types

You can create your error types by extending the built-in Error class.

Example- 

class ValidationError extends Error {
   constructor(message) {
       super(message);
       this.name = "ValidationError";
   }
}
function validateInput(input) {
   if (input < 0) {
       throw new ValidationError("Input cannot be negative");
   }
}
try {
   validateInput(-1);
} catch (error) {
   if (error instanceof ValidationError) {
       console.error("Validation Error: ", error.message);
   } else {
       console.error("Unknown Error: ", error.message);
   }
}

 

Asynchronous error handling


Promises- Promises have their own way of catch resolving debugging.

someAsyncFunction()
   .then(result => {
       console.log(result);
   })
   .catch(error => {
       console.error("Promise error: ", error.message);
   });

 

async/await- When using async functions, you can handle errors with try...catch.

async function fetchData() {
   try {
       let response = await fetch("https://api.example.com/data");
       let data = await response.json();
       console.log(data);
   } catch (error) {
       console.error("Async error: ", error.message);
   }
}
fetchData();

 

Best Practices

Always Handle Errors- never leave mistakes unchecked; Always use try…catch or promise catch blocks.
Provide Useful Error Messages- Make sure your error messages are clear and informative.
Log Errors Appropriately- Use logging to track errors but avoid disclosing sensitive information.
Clean Up Resources- The finally use blocking or other methods to clean objects (e.g. files or close network connections).
 

Also, Read: Explation the concept OPPs in JavaScrpipt


Hi! This is Ashutosh Kumar Verma. I am a software developer at MindStick Software Pvt Ltd since 2021. I have added some new and interesting features to the MindStick website like a story section, audio section, and merge profile feature on MindStick subdomains, etc. I love coding and I have good knowledge of SQL Database.

Leave Comment

Comments

Liked By